//
//  AppDelegate.swift
//  Sina
//
//  Created by 王杰 on 15/11/8.
//  Copyright © 2015年 王杰. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        let account = UserAccount.loadAccount()
        print(account)
        window = UIWindow(frame : UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        
        window?.makeKeyAndVisible()
        //设置主题色
        setThemeColor()
        //注册一个通知
        registerNotification()
        print("------------")
        //        print(isNewVersion())
//        let nav = UINavigationController(rootViewController: ComposeViewController())
        window?.rootViewController = defaultRootController()
        return true
    }
    //监听通知
    private func registerNotification() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToRootVC:", name: AppSwitchRootViewControler, object: nil)
        
    }
    
    @objc private func switchToRootVC(n:NSNotification){
        
        print(n)
        
        if(n.object as? String) != nil{
            
            window?.rootViewController = WelComeViewController()
            return
        }
        
        window?.rootViewController = MainTableViewController()
        
    }
    
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
    //MARK: 判断用户是否登陆 并且是否是更新版本
    private func defaultRootController() -> UIViewController {
        if UserAccountViewModel().userLogin {
            
            
            return isNewVersion() ? NewFeatureViewController() : WelComeViewController()
        }
        return MainTableViewController()
    }
    
    
    private func setThemeColor() {
        UINavigationBar.appearance().tintColor = themeColor
        UITabBar.appearance().tintColor = themeColor
    }
    //MARK: 检测是否是最新版本
    private func isNewVersion() ->Bool {
        
        let versionStr = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        let versionNum = Double(versionStr)
        //获取旧版本信息
        let key = "sandBoxKey"
        let userdefaults = NSUserDefaults.standardUserDefaults()
        let lastVersion = userdefaults.doubleForKey(key)
        print(lastVersion)
        
        userdefaults.setDouble(versionNum!, forKey: key)
        userdefaults.synchronize()
        
        return versionNum! > lastVersion
    }
    
}
























